#!/bin/bash
CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
TOP_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )"
MIRROS=registry.aliyuncs.com/google_containers

yq_add_array() {
  local file=$1
  local yqPath=$2
  local data=$3
  local new=$(echo "[\"$data\"]" | sed 's/,/\",\"/g')
  yq -i "$yqPath += $new | $yqPath |= unique"  -o json $file
}

localDataPath=/tmp/data/registry
localRegistry=edge.local.io:5000
remoteRegistry=${remoteRegistry:-""}
remoteRegistryIp=${remoteRegistryIp:-""}

if [ -n "$remoteRegistry" ] && [ -n "$remoteRegistryIp" ]; then
  sed -i "/$remoteRegistry/d" /etc/hosts
  echo "$remoteRegistryIp $remoteRegistry" >> /etc/hosts
  yq_add_array /etc/docker/daemon.json .insecure-registries $remoteRegistry
fi

yq_add_array /etc/docker/daemon.json .insecure-registries edge.local.io:5000
systemctl restart docker

if [ -n "$(docker ps --filter "name=^registry$" -q)" ] ; then
  docker stop registry
  docker rm registry
fi

mkdir -p $localDataPath
rm -rf $localDataPath/*
rm -rf $CUR_DIR/docker.tar.gz

docker run -d \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  -v /tmp/data/registry:/var/lib/registry \
  registry:2

while true; do
  sleep 1
  docker port registry
  if [ $? -eq 0 ]; then
    break
  fi	  
done

sed -i "/${localRegistry%%:*}/d" /etc/hosts
echo "127.0.0.1 ${localRegistry%%:*}" >> /etc/hosts
docker logout ${localRegistry}

echo "pack images: local=$localRegistry, remote=$remoteRegistry"

bash $CUR_DIR/build-registry.sh --local=$localRegistry --remote=$remoteRegistry

if [ -d $localDataPath/docker ]; then
  cd $localDataPath/
  tar zcvf $CUR_DIR/docker.tar.gz  docker/ > /dev/null
  cd -
fi

docker stop registry
docker rm registry

